/**
 * 
 */
package com.ls.x.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.ImageView.ScaleType;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;

import com.ls.x.R;
import com.ls.x.tool.DatabaseHelper;
import com.ls.x.tool.Debug;

/**
 * @author 李靖
 * 
 */
public class ContentShowActivity extends Activity {

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onDestroy() {
		Debug.logForLijing("ContentShowActivity.onDestroy");
		super.onDestroy();
		if (bitmap != null) {
			bitmap.recycle();
		}
		if (dbHelper != null) {
			dbHelper.close();
		}
		if (db != null) {
			db.close();
		}
	}

	TextView title = null;
	TextView summary = null;
	TextView other_context = null;
	TextView close_remark = null;

	private DatabaseHelper dbHelper = null;
	private SQLiteDatabase db = null;
	private Cursor cursor = null;
	private LinearLayout imageListLayout;
	private ImageView iv_image;
	private TextView tv_image_note;
	private Bitmap bitmap;
	private Map<Integer, ArrayList<View>> imageShowMap;
	private ArrayList<View> viewShowList;
	private long context_id;

	private ImageView iv_voice;
	private TextView tv_voice_note;
	private String voice_path;
	private String voice_note;
	private ArrayList<String> voiceDataList;
	private int voiceId;
	private TableRow voiceListLayoutRow;
	private Map<Integer, ArrayList<String>> voiceDataMap;
	private TableLayout voiceListLayout;
	private Map<Integer, View> voiceShowMap;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.page_show_content);

		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		context_id = bundle.getLong("context_id");

		title = (TextView) findViewById(R.id.txt_show_title);
		summary = (TextView) findViewById(R.id.txt_show_summary);
		other_context = (TextView) findViewById(R.id.txt_show_other);
		close_remark = (TextView) findViewById(R.id.txt_show_close_remark);

		dbHelper = DatabaseHelper.getDBhelper(ContentShowActivity.this);
		db = dbHelper.getReadableDatabase();

		voiceListLayout = (TableLayout) findViewById(R.id.tblayout_show_page_voice_list);

		setEditorViews();
		setImageViews();
		setVoiceViews();

		// 完成按钮
		Button btn_finish = (Button) findViewById(R.id.btn_finish);
		btn_finish.setOnClickListener(new FinishBtnListener());

		// 推迟按钮
		Button btn_delay = (Button) findViewById(R.id.btn_delay);
		btn_delay.setOnClickListener(new DelayBtnListener());
	}

	private void setEditorViews() {
		cursor = db.rawQuery("select * from context where id = " + context_id,
				null);
		if (cursor.moveToNext()) {
			title.setText(cursor.getString(cursor.getColumnIndex("title")));
			summary.setText(cursor.getString(cursor.getColumnIndex("summary")));
			close_remark.setText(cursor.getString(cursor
					.getColumnIndex("remark")));
			other_context.setText(cursor.getString(cursor
					.getColumnIndex("class"))
					+ "\n"
					+ cursor.getString(cursor.getColumnIndex("repeat"))
					+ "\n"
					+ cursor.getString(cursor.getColumnIndex("level"))
					+ "\n"
					+ new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date(
							Long.parseLong(cursor.getString(cursor
									.getColumnIndex("start_date")))))
					+ "\n"
					+ cursor.getString(cursor.getColumnIndex("end_date"))
					+ "\n"
					+ cursor.getString(cursor.getColumnIndex("postpone_date")));
		}
	}

	private void setImageViews() {
		imageListLayout = (LinearLayout) findViewById(R.id.llayout_show_page_image_list);
		cursor = db.rawQuery("select * from image where context_id = "
				+ context_id, null);
		int imageId = 1;
		imageShowMap = new HashMap<Integer, ArrayList<View>>();
		while (cursor.moveToNext()) {
			iv_image = new ImageView(ContentShowActivity.this);
			tv_image_note = new TextView(ContentShowActivity.this);
			viewShowList = new ArrayList<View>();
			String image_path = cursor.getString(cursor
					.getColumnIndex("image_path"));
			String image_note = cursor.getString(cursor
					.getColumnIndex("image_note"));
			// 设置图片显示ImageView
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inSampleSize = 4;
			bitmap = BitmapFactory.decodeFile(image_path, opts);
			LinearLayout.LayoutParams ivParams = new LinearLayout.LayoutParams(
					500, 500);
			iv_image.setId(imageId);
			iv_image.setLayoutParams(ivParams);
			iv_image.setImageBitmap(bitmap);
			iv_image.setScaleType(ScaleType.FIT_CENTER);

			// 设置图片说明TextView
			LayoutParams tvParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT);
			tv_image_note.setLayoutParams(tvParams);
			tv_image_note.setGravity(Gravity.CENTER);
			tv_image_note.setText(image_note);
			viewShowList.add(iv_image);
			viewShowList.add(tv_image_note);
			imageShowMap.put(imageId, viewShowList);
			imageId++;
		}
		Log.d("lijing", "imageShowMap.size():" + imageShowMap.size());
		imageListLayout.removeAllViews();
		Object[] key_arr = imageShowMap.keySet().toArray();
		Arrays.sort(key_arr);
		for (Object key : key_arr) {
			ArrayList<View> value = imageShowMap.get(key);
			if (value != null) {
				imageListLayout.addView(value.get(0));
				imageListLayout.addView(value.get(1));
			}
		}
	}

	private void initializeImageVariables() {
		if (voiceShowMap == null) {
			voiceShowMap = new HashMap<Integer, View>();
		}
		if (voiceDataMap == null) {
			voiceDataMap = new HashMap<Integer, ArrayList<String>>();
		}
	}

	private void setVoiceViews() {
		initializeImageVariables();
		cursor = db.rawQuery("select * from voice where context_id = "
				+ context_id, null);
		while (cursor.moveToNext()) {
			voice_path = cursor.getString(cursor.getColumnIndex("voice_path"));
			voice_note = cursor.getString(cursor.getColumnIndex("voice_note"));
			voiceId = voiceShowMap.size() + 1;
			setVoiceData();
			iv_voice = new ImageView(ContentShowActivity.this);
			tv_voice_note = new TextView(ContentShowActivity.this);
			iv_voice.setId(voiceId);
			iv_voice.setImageResource(R.drawable.record);
			iv_voice.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					String clickVoiceFilePath = "";
					clickVoiceFilePath = voiceDataMap.get(v.getId()).get(0)
							.toString();

					Intent intent = new Intent("android.intent.action.VIEW");
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.putExtra("oneshot", 0);
					intent.putExtra("configchange", 0);
					Uri uri = Uri.fromFile(new File(clickVoiceFilePath));
					intent.setDataAndType(uri, "audio/*");
					startActivity(intent);
				}
			});

			tv_voice_note.setText(voice_note);
			voiceListLayoutRow = new TableRow(ContentShowActivity.this);
			voiceListLayoutRow.setGravity(Gravity.CENTER_VERTICAL);
			voiceListLayoutRow.addView(iv_voice);
			voiceListLayoutRow.addView(tv_voice_note);
			voiceShowMap.put(voiceId, voiceListLayoutRow);

			// 更新界面
			voiceListLayout.removeAllViews();
			Object[] key_arr = voiceShowMap.keySet().toArray();
			Arrays.sort(key_arr);
			for (Object key : key_arr) {
				View value = voiceShowMap.get(key);
				if (value != null) {
					voiceListLayout.addView(value);
				}
			}
		}

	}

	private void setVoiceData() {
		voiceDataList = new ArrayList<String>();
		voiceDataList.add(0, voice_path);
		voiceDataList.add(1, voice_note);
		voiceDataMap.put(voiceId, voiceDataList);
	}

	// 完成按钮事件监听器
	class FinishBtnListener implements OnClickListener {
		final Builder builder = new AlertDialog.Builder(
				ContentShowActivity.this);

		@Override
		public void onClick(View v) {
			builder.setTitle("完成备注");
			TableLayout finishNote = (TableLayout) getLayoutInflater().inflate(
					R.layout.dialog_add_note_to_finish, null);
			builder.setView(finishNote);

			// 为对话框设置”确定“按钮
			// 注意，为了跟View中的button的事件却分，需要在OnClickListener前面加上DialogInterface
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							System.out.println("点击了确定按钮");
						}
					});
			// 为对话框设置”确定“按钮
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							Log.d("lijing", "点击了取消按钮");
						}
					});
			builder.create().show();
		}
	}

	// 推迟按钮事件监听
	class DelayBtnListener implements OnClickListener {

		final Builder builder = new AlertDialog.Builder(
				ContentShowActivity.this);

		private int year;
		private int month;
		private int day;
		private int hour;
		private int minute;

		@Override
		public void onClick(View v) {
			builder.setTitle("推迟到");
			TableLayout delayNote = (TableLayout) getLayoutInflater().inflate(
					R.layout.picker_datetime, null);
			// 上面一段分解开来即如下代码
			// LayoutInflater inflater = getLayoutInflater();
			// View view = inflater.inflate(R.layout.delaynote, null);
			// TableLayout delayNote = (TableLayout)view;

			builder.setView(delayNote);
			// 获得出线在对话框中的DatePicker和TimePicker
			DatePicker datePicker = (DatePicker) delayNote
					.findViewById(R.id.datePicker);
			TimePicker timePicker = (TimePicker) delayNote
					.findViewById(R.id.timePicker);
			Calendar c = Calendar.getInstance();
			year = c.get(Calendar.YEAR);
			month = c.get(Calendar.MONTH) + 1;
			day = c.get(Calendar.DAY_OF_MONTH);
			hour = c.get(Calendar.HOUR);
			minute = c.get(Calendar.MINUTE);
			Log.d("lijing", datePicker + " " + timePicker);
			datePicker.init(year, month, day, new OnDateChangedListener() {

				@Override
				public void onDateChanged(DatePicker view, int year,
						int monthOfYear, int dayOfMonth) {
					DelayBtnListener.this.year = year;
					DelayBtnListener.this.month = month;
					DelayBtnListener.this.day = day;
				}
			});

			timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {

				@Override
				public void onTimeChanged(TimePicker view, int hourOfDay,
						int minute) {
					DelayBtnListener.this.hour = hour;
					DelayBtnListener.this.minute = minute;
				}
			});

			// 为对话框设置”确定“按钮
			// 注意，为了跟View中的button的事件却分，需要在OnClickListener前面加上DialogInterface
			builder.setPositiveButton(R.string.text_dialog_ok,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							Log.d("lijing", "点击了确定按钮");
							Toast.makeText(
									ContentShowActivity.this,
									"推迟到：" + year + "-" + month + "-" + day
											+ " " + hour + ":" + minute,
									Toast.LENGTH_SHORT).show();
						}
					});
			// 为对话框设置”确定“按钮
			builder.setNegativeButton(R.string.text_dialog_cancel,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							Log.d("lijing", "点击了取消按钮");
						}
					});
			builder.create().show();
		}
	}
}
